/**
 * Created by maiseries on 2017/10/15.
 */
import React from 'react';
import {
    StyleSheet,
    View,
    ScrollView,
    Image,
    Text,
    TouchableOpacity,
    TouchableWithoutFeedback,
    DeviceEventEmitter,
    Share
} from 'react-native';

import NavBar from '../components/NavBarView'
import HorizontalMenu from '../components/HorizontalMenuView'
import Constants from '../config/Constants'
import ManagerService from '../services/Manager'
import SystemService from '../services/System'

let _self = null, _navigation = null, _subscription = null, _subscriptionForMessage = null;

const authIcons = {
    '01': require('../sources/icon_mine_auth_ing.png'),
    '09': require('../sources/icon_mine_auth_to.png'),
    '08': require('../sources/icon_mine_auth_to.png'),
    '02': require('../sources/icon_mine_auth_ed.png'),
    '03': require('../sources/icon_mine_auth_to.png'),
}

class Views extends React.Component {

    constructor(props) {
        super(props);
        _self = this;
        _navigation = this.props.navigation;
        this.state = {
            isLogged: typeof user.loginState === 'boolean' ? user.loginState : false,
            summary: {
                institution_name: '',
                audit_state: '01'
            },
            messages: false
        }
    }

    componentWillMount() {

    }

    componentDidMount() {
        _self.loginListener();
        _self.messageListener();
        _self.summary();
        _self.message();
    }

    componentWillUnmount() {
        _subscription.remove();
        _subscriptionForMessage.remove();
    }

    loginListener() {
        _subscription = DeviceEventEmitter.addListener(Constants.LISTENER_LOGGING, () => {
            _self.setState({
                isLogged: user.loginState
            })
            _self.summary();
        })
    }

    messageListener() {
        _subscriptionForMessage = DeviceEventEmitter.addListener(Constants.LISTENER_MESSAGES, () => _self.message())
    }

    async message() {
        const {result, message, data} = await SystemService.aggregateMessage();
        if (result) {
            _self.setState({
                messages: data.message
            })
        } else {
            Toast.show(message);
        }
    }

    async summary() {
        if (user.loginState) {
            const {result, message, data} = await ManagerService.summary();
            if (result) {
                _self.setState({
                    summary: data
                })
            } else {
                Toast.show(message);
            }
        }
    }

    share() {
        Share.share({
            message: 'React Native | A framework for building native apps using React'
        })
            .then(()=>{})
            .catch((error) => this.setState({result: 'error: ' + error.message}));
    }

    skip(route, params) {
        _navigation.navigate(route, params)
    }

    render() {
        return (
            <View style={[styles.container, base.clientWH]}>
                <NavBar
                    back={false}
                    host={this}
                    leftIcon={require('../sources/icon_mine_setting.png')}
                    leftEvent={() => this.skip('Setting')}
                    rightPoint={this.state.messages}
                    rightIcon={require('../sources/icon_mine_message.png')}
                    rightEvent={() => this.skip('MessageList')}/>
                <ScrollView style={styles.listBox}>
                    <Image resizeMode={'cover'} source={require('../sources/image_demand_banner.png')}
                           style={[base.rowCC, styles.topBox]}>
                        {
                            this.state.isLogged ?
                                <TouchableWithoutFeedback onPress={() => this.skip('AuthList')}>
                                    <View style={[base.rowCC, styles.loginBox]}>
                                        <Image
                                            resizeMode={'contain'}
                                            style={styles.loginHead}
                                            source={require('../sources/icon_mine_head.png')}/>
                                        <View style={styles.loginTextBox}>
                                            <Text allowFontScaling={false} style={[styles.title, {
                                                color: this.state.summary.audit_state === '02' ? layout.MAIN_COLOR : layout.FORM_AUX_FONT_COLOR
                                            }]}>{this.state.summary.audit_state === '02' ? this.state.summary.institution_name : '暂无认证'}</Text>
                                            <Image
                                                resizeMode={'contain'}
                                                style={styles.authIcon}
                                                source={authIcons[this.state.summary.audit_state]}/>
                                        </View>
                                    </View>
                                </TouchableWithoutFeedback> :
                                <View style={[base.rowCC, styles.loginBox]}>
                                    <TouchableOpacity activeOpacity={layout.TOUCH_OPACITY_ACTIVE}
                                                      onPress={() => this.skip('Login', {tab: 'login'})}>
                                        <View style={styles.loginBtn}>
                                            <Text allowFontScaling={false} style={styles.loginBtnText}>登录</Text>
                                        </View>
                                    </TouchableOpacity>
                                    <TouchableOpacity activeOpacity={layout.TOUCH_OPACITY_ACTIVE}
                                                      onPress={() => this.skip('Login', {tab: 'register'})}>
                                        <View style={styles.registerBox}>
                                            <Text allowFontScaling={false} style={styles.registerBtnText}>注册</Text>
                                        </View>
                                    </TouchableOpacity>
                                </View>
                        }
                    </Image>
                    <View style={styles.listGroup}>
                        <HorizontalMenu
                            onPress={() => this.skip('DemandList')}
                            text="我的需求"
                            icon={require('../sources/icon_mine_demand.png')}/>
                        <HorizontalMenu
                            onPress={() => this.skip('AssetList')}
                            text="我的资产"
                            icon={require('../sources/icon_mine_asset.png')}/>
                        <HorizontalMenu
                            last={true}
                            onPress={() => this.skip('AuthList')}
                            text="认证资料"
                            icon={require('../sources/icon_mine_auth.png')}/>
                    </View>
                    <View style={styles.listGroup}>
                        <HorizontalMenu
                            onPress={() => this.skip('AboutUs')}
                            text="关于麦乐"
                            icon={require('../sources/icon_mine_about.png')}/>
                        {/*<HorizontalMenu*/}
                            {/*onPress={() => this.skip('HelpList')}*/}
                            {/*text="帮助中心"*/}
                            {/*icon={require('../sources/icon_mine_help.png')}/>*/}
                        <HorizontalMenu
                            onPress={() => this.skip('BusinessForm')}
                            text="商务合作"
                            icon={require('../sources/icon_mine_business.png')}/>
                        <HorizontalMenu
                            last={true}
                            onPress={() => this.share()}
                            text="分享好友"
                            icon={require('../sources/icon_mine_share.png')}/>
                    </View>
                </ScrollView>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        backgroundColor: layout.MAIN_BACKGROUND_COLOR
    },
    topBox: {
        width: layout.MAX_WIDTH,
        height: layout.height(270),
        backgroundColor: layout.MAIN_AUX_COLOR
    },
    loginBox: {
        paddingHorizontal: layout.width(60),
        paddingBottom: layout.GAP_VERTICAL_LARGE
    },
    loginHead: {
        width: layout.width(117),
        height: layout.height(117)
    },
    loginTextBox: {
        flex: 1,
        paddingLeft: layout.GAP_HORIZONTAL_MID
    },
    title: {
        paddingBottom: layout.GAP_VERTICAL_MID,
        color: layout.MAIN_COLOR,
        fontSize: layout.font(36),
        fontWeight: '700'
    },
    authIcon: {
        width: layout.width(142),
        height: layout.height(44)
    },
    loginBtn: {
        marginRight: layout.width(80),
        paddingHorizontal: layout.width(60),
        paddingVertical: layout.height(16),
        borderRadius: layout.height(76),
        borderWidth: layout.LINE_WIDTH * 2,
        borderColor: layout.MAIN_COLOR
    },
    loginBtnText: {
        fontSize: layout.font(36),
        color: layout.MAIN_COLOR,
        fontWeight: '700'
    },
    registerBox: {
        paddingHorizontal: layout.width(60),
        paddingVertical: layout.height(16),
        borderRadius: layout.height(76),
        borderWidth: layout.LINE_WIDTH * 2,
        borderColor: layout.MAIN_COLOR,
        backgroundColor: layout.MAIN_COLOR
    },
    registerBtnText: {
        fontSize: layout.font(36),
        color: '#fff',
        fontWeight: '700'
    },
    listBox: {
        flex: 1,
    },
    listGroup: {
        marginBottom: layout.GAP_VERTICAL_SMALL,
        backgroundColor: '#fff'
    }
})

//路由
const Mine = {
    screen: Views,
    path: 'sign/mine',
    navigationOptions: {
        header: null,
        tabBarLabel: '我的',
        tabBarIcon: ({focused, tintColor}) => (
            focused ? <Image
                source={require('../sources/icon_tab_mine_selected.png')}
                style={{
                    width: layout.width(60),
                    height: layout.height(60)
                }}
                resizeMode={'contain'}
            /> : <Image
                source={require('../sources/icon_tab_mine_unselect.png')}
                style={{
                    width: layout.width(60),
                    height: layout.height(60)
                }}
                resizeMode={'contain'}
            />
        ),
    },
    name: 'Mine',
    sign: false
};

export default Mine;